<?php

namespace app\api\controller\shop;


use app\admin\model\Cmdlog;
use app\admin\model\money\Platform;
use app\admin\model\Org;
use app\admin\model\Shop;
use app\admin\model\Shopbalanceprofit;
use app\admin\model\Shopcharge;
use app\admin\model\Shopdevice;
use app\admin\model\Shopdou;
use app\admin\model\Shopmeituan;
use app\admin\model\Shopmno;
use app\admin\model\Shopmtdyprofit;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shopstaff;
use app\admin\model\Shoptableorder;
use app\admin\model\Useragent;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Usercard;
use app\admin\model\Userdoucode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userwithdraw;
use app\api\service\AirService;
use app\api\service\BalanceService;
use app\api\service\BankService;
use app\api\service\CommonService;
use app\api\service\TableService;
use app\api\service\VbillService;
use app\common\controller\Api;
use fast\Http;
use OSS\OssClient;
use think\Db;

/**
 *
 */
class Shoptable extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    //添加台桌
    public function add()
    {

        $name = $this->request->param('name');
        $shop_id = $this->request->param('shop_id');
        $min_pay = $this->request->param('min_pay');
        $ya_amount = $this->request->param('ya_amount');
        $logo = $this->request->param('logo');
        $time1 = $this->request->param('time1');
        $price1 = $this->request->param('price1');
        $time2 = $this->request->param('time2');
        $price2 = $this->request->param('price2');
        $id = $this->request->param('id');
        $weigh = $this->request->param('weigh');
        if (!$weigh) $weigh = 1;


        $db = array();
        $db['name'] = $name;
        $db['logo'] = $logo;
        $db['ya_amount'] = $ya_amount;
        $db['min_amount'] = $min_pay;
        $db['shop_id'] = $shop_id;
        $db['weigh'] = $weigh;

        $obj = array();
        $obj['time1'] = $time1;
        $obj['price1'] = $price1;
        $obj['time2'] = $time2;
        $obj['price2'] = $price2;
        $db['rule'] = json_encode($obj);

        $shopTableModel = new \app\admin\model\Shoptable();
        if ($id != "") {
            $shopTableModel->where('id', $id)->update($db);
        } else {
            $shopTableModel->insert($db);
        }
        $this->success('成功');

    }


    //获取台桌列表
    public function getList()
    {

        $shop_id = $this->request->param('shop_id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $list = $shopTableModel->where('shop_id', $shop_id)->order('id', 'asc')->select();


        $shopDeviceModel = new Shopdevice();


        foreach ($list as $key => $val) {

            $device = $shopDeviceModel->where('shop_id', $val['shop_id'])->where('room_id', $val['id'])->where('device_type', 'tq')->find();
            if ($device) {
                $list[$key]['bind'] = 1;
            } else {
                $list[$key]['bind'] = -1;

            }

            $list[$key]['logo'] = cdnurl($val['logo'], true);
            $rule = json_decode($val['rule'], true);
            $list[$key]['rule'] = $rule;

            $list[$key]['check'] = true;

        }

        $this->success('', $list);
    }

    //绑定设备
    public function bindDevice()
    {

        $sn = $this->request->param('sn');
        $shop_id = $this->request->param('shop_id');
        $room_id = $this->request->param('room_id');

        $user = $this->auth->getUser();
        $deviceModel = new Shopdevice();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $shop_id)->where('user_id', $user['id'])->find();

        error_log("==d==" . json_encode($shop));
        if (!$shop) $this->error("无权限操作");

        $d = $deviceModel->where('device_sn', $sn)->find();

        if ($d['user_id'] != $user['id']) {
            $this->error("无权限操作");
        }
        if ($d['bind_status'] != -1) {
            $this->error("先解绑再操作");
        }

        $deviceModel->where('id', $d['id'])->update(['shop_id' => $shop_id, 'room_id' => $room_id, 'bind_status' => 1]);

        $this->success('');
    }

    //台桌详情
    public function detail()
    {

        $id = $this->request->param('id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $table = $shopTableModel->where('id', $id)->find();
        $shop = $shopModel->where('id', $table['shop_id'])->find();
        $table['logo_path'] = $table['logo'];
        $table['logo'] = cdnurl($table['logo'], true);

        $table['rule'] = json_decode($table['rule'], true);
        $table['shopName'] = $shop['name'];

        $this->success('', $table);
    }

    //订单列表
    public function getOrderList()
    {

        $page = $this->request->param('page');
        $shop_id = $this->request->param('shop_id');
        $status = $this->request->param('status');
        $orderNo = $this->request->param('orderNo');
        $startTime = $this->request->param('startTime');
        $shopOrderModel = new Shoptableorder();

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        $where['shop_id'] = $shop_id;
        if ($status != '') {
            $where['Shoptableorder.status'] = array('=', $status);
        }
        if ($orderNo != "") {
            $where['order_no'] = array('like', "%" . $orderNo . "%");
        }
        if ($startTime != "" && $startTime != "时间选择") {
            $start = strtotime($startTime . " 00:00");
            $end = strtotime($startTime . " 23:59");
            $where['create_time'] = array("between", array($start, $end));
        }
        $list = $shopOrderModel->with(['user'])->where('Shoptableorder.status', "<>", 'paying')->where($where)->order('create_time', 'desc')->limit($offset, $limit)->select();
        foreach ($list as $key => $val) {

            $val['user']->hidden(['password', 'salt']);
            $list[$key]['order_no_str'] = substr($val['order_no'], 0, 5) . "*****" . substr($val['order_no'], strlen($val['order_no']) - 4, 4);

            $list[$key]['book_start'] = date("Y-m-d H:i", $val['book_start']);
            $list[$key]['book_end'] = date("Y-m-d H:i", $val['book_end']);
            $list[$key]['create_time_txt'] = date("Y-m-d H:i", $val['create_time']);

            $list[$key]['status_txt'] = $shopOrderModel->formatStatus($val['status']);
        }
        $this->success('', $list);

    }


    //结束订单
    public function overOrder()
    {

        $user = $this->auth->getUser();
        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();
        $from = $this->request->param('from');

        if ($order['status'] == 'done') {

            $this->error("此订单此完成 无需操作");
        }
        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

        if ($order['book_end'] == -1) {
            if ($from != 'task') {
//                if (($order['is_qiu'] == -1 || $order['is_lock'] == -1) && $device['is_weight'] == 1) {
//
//                    $this->error("", "", "2");
//                }
            }
            $tableModel = new \app\admin\model\Shoptable();
            $table = $tableModel->where('id', $order['table_id'])->find();
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();
            $rule = json_decode($table['rule'], true);
            $book_end = time();
            $minute = floor(($book_end - $order['book_start']) % 86400 / 60);
            $hour = ceil($minute / 60);
            $start = date("H", $order['book_start']);


            $time1List = explode("~", $rule['time1']);
            if (count($time1List) == 1) {
                $startTime1 = explode("-", $rule['time1'])[0];
                $endTime1 = explode("-", $rule['time1'])[1];
            } else {
                $startTime1 = explode("~", $rule['time1'])[0];
                $endTime1 = explode("~", $rule['time1'])[1];
            }


            $time2List = explode("~", $rule['time2']);
            if (count($time2List) == 1) {
                $startTime2 = explode("-", $rule['time2'])[0];
                $endTime2 = explode("-", $rule['time2'])[1];
            } else {
                $startTime2 = explode("~", $rule['time2'])[0];
                $endTime2 = explode("~", $rule['time2'])[1];
            }
            $startTime1 = intval($startTime1);
            $endTime1 = intval($endTime1);


            $startTime2 = intval($startTime2);
            $endTime2 = intval($endTime2);
            $slots = array();

            if ($endTime1 < $startTime1) {
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;

            } else {
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
            }

            if ($endTime2 < $startTime2) {
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;

            } else {
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
            }

            $hour = floor($minute / 60);

            $orderAmount = $order['pay_amount'];
            $pay_amount = 0;
            if ($order['mt_code'] != '' || $order['dou_code'] != '' || $order['tuan_id'] != -1) {

                $orderAmount = 0;
                $amount = $order['amount'];
                $pay_amount = 0;
            } else {
                $amount = get_charge($start, $hour, $slots, $minute);
                if ($amount <= $table['min_amount']) {
                    $amount = $table['min_amount'];

                }

                if ($amount > $order['ya_amount'] && $order['pay_amount'] > 0) {
                    $amount = $order['ya_amount'];//先暂时这样处理
                }
                $orderAmount = $amount;

            }

            //1.计算费用
            $tableModel->where('id', $order['table_id'])->update(['status' => 'free']);
            //2.断电

            $mno = $this->mno;
            $refundAmount = 0;
            $dbBalance = 0;


            if ($orderAmount > 0) {

                $userBalanceModel = new Userbalance();

                //如果是余额开台
                if ($order['balance'] > 0 && $order['ya_amount'] == 0) {
                    $pay_amount = 0;
                    $refundAmount = 0;
                    $dbBalance = $amount;
                    $b = $userBalanceModel->where('order_id', $order['id'])->where('from', 'tq')->find();
                    if ($b) {
                        $userBalanceModel->where('id', $b['id'])->update(['amount' => $dbBalance]);
                    }
                } else {
                    $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                    if ($balance < 0) $balance = 0;
                    $shopOrderProfitModel = new Shoporderprofit();
                    if ($balance == 0) {
                        //3. 发分润
                        $pay_rate = formatMoney($shop['pay_rate'] * $amount / 100);
                        $rate = formatMoney($shop['ratio'] * $amount / 100);
                        $shopProfit = $amount - $pay_rate - $rate;
                        $refundAmount = $order['ya_amount'] - $amount;
                        $pay_amount = $amount;
                        $dbBalance = 0;
                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                            'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                    } else {

                        if ($amount <= $balance) {
                            $refundAmount = $order['ya_amount'];
                            $dbBalance = $amount;
                            $pay_amount = 0;
                            error_log("===amount=====" . $amount);
                        } else {
                            $refundAmount = $order['ya_amount'] - ($amount - $balance);
                            $dbBalance = $balance;
                            $dbAmount = $amount - $balance;
                            $pay_amount = $order['ya_amount'] - $refundAmount;

                            $pay_rate = formatMoney($shop['pay_rate'] * $dbAmount / 100);
                            $rate = formatMoney($shop['ratio'] * $dbAmount / 100);
                            $shopProfit = $amount - $pay_rate - $rate;

                            if ($shopProfit > 0) {
                                $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                    'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($shopProfit)]);
                            }

                        }
                        if ($dbBalance > 0) {
                            $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out', 'amount' => $dbBalance, 'mark' => '台球抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id'], 'b_type' => 'order', 'from' => 'tq']);
                        }
                    }
                    //部分退款
                    $shopMnoModel = new Shopmno();
                    $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
                    if ($shopMno && $shopMno['ratio'] == 100) {
                        $mno = $shopMno['mno'];
                    }
                    error_log(formatMoney($refundAmount) . "=====refundAmount==" . $refundAmount);

                    $req = array();
                    $req['mno'] = $mno;
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $order['order_no'];
                    $req['amt'] = formatMoney($refundAmount);

                    if ($refundAmount > 0) {
                        error_log("==refund req===" . json_encode($req));
                        $vbillService = new VbillService();
                        $ret = $vbillService->refund($req);
                        error_log("=====refund=sxf==" . $ret);
                    }
                }


            } else {
                //扣余额

                if ($order['dou_code'] != '' || $order['mt_code'] != "") {

                } else {
                    $userBalanceModel = new Userbalance();
                    $db = array();
                    $db['user_id'] = $order['user_id'];
                    $db['type'] = "out";
                    $db['amount'] = $amount;
                    $db['mark'] = $order['shop_name'] . $order['table_name'] . "抵扣";
                    $db['create_time'] = time();
                    $db['shop_id'] = $order['shop_id'];
                    $db['order_id'] = $order['id'];
                    $db['b_type'] = "order";
                    $db['from'] = "tq";
                    $userBalanceModel->insert($db);

                }

            }
            $tableOrderModel->where('id', $order['id'])->update(['book_end' => $book_end, 'amount' => $amount, 'pay_amount' => $pay_amount, 'status' => 'done', 'refund_amount' => $refundAmount, 'is_done' => 1, 'update_time' => time(), 'balance' => $dbBalance]);
            //关闭
            $tableOrderModel->where('id', $order['id'])->update(['update_time' => time()]);
        }

        $tableOrderModel->where('id', $order['id'])->update(['status' => 'done']);


        if ($device['version'] == 1) {
            $req = array();
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];

            $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        } else if ($device['version'] == 2) {
            $req['sec'] = 0;
            $req['voice'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        } else if ($device['version'] == 3) {
            $req = array();
            $req['sec'] = 0;
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];
            $ret = http_post_json($this->tqV3CmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        }


        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);

        $airService = new AirService();
        $airService->airCheck2($order['shop_id'], 0);
        $airService->airCheckV2($order['shop_id'], $order['table_id']);
        $this->success('成功');

    }

    //更改台桌
    public function updateOrderTable()
    {

        $order_no = $this->request->param('order_no');
        $id = $this->request->param('id');

        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no', $order_no)->find();
        if ($order['table_id'] == $id) {
            $this->error("当前台桌和订单台桌一致,无需更改");
        }
        if ($order['status'] != "doing") {
            $this->error("当前订单状态不允许更改!");
        }
        $shopTableModel = new \app\admin\model\Shoptable();
        $table = $shopTableModel->where('id', $id)->find();
        if ($table['status'] == 'busy') {
            $this->error("此台桌正在开台中，不支持更改");
        }
        $tableOrderModel->where('id', $order['id'])->update(['table_id' => $id, 'table_name' => $table['name']]);

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();

        $tableService = new TableService();
        //该方法关台后，回调会导致订单结束
        //$tableService->close($order, $device);
        $tableService->updateTableClose($order, $device);

        //开新的台桌，通过查询更新后的订单，查询新的台桌Id
        $order = $tableOrderModel->where('order_no', $order_no)->find();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
        $tableService->open($order, $device);

        $airService = new AirService();
        $airService->airCheck($order['shop_id']);
        $airService->airCheckV2($order['shop_id'], $order['table_id']);

        $this->success('成功');

    }


    public function getTableCodeUrl()
    {

        $table_id = $this->request->param('table_id');

        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id', $table_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $table['shop_id'])->find();

        $orgModel = new Org();
        $org = $orgModel->where('id', $shop['org_id'])->find();

        $app_id = $org['app_id'];
        $app_secret = $org['app_secret'];


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $app_id . "&secret=" . $app_secret;
        $ret = Http::get($url);
        $obj = json_decode($ret, true);
        $token = $obj['access_token'];


        $scene = $shop['id'] . "-" . $table_id;
        error_log("==scene===" . $scene);

        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => 'pages/order/ballSubmit',

        ];
        $name = "table_" . $shop['id'] . "_" . $table_id;

        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);

        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;
        $filename = './uploads/' . $name . '.jpg';

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {

            if ($table['qr_code'] != '') {

                $url = cdnurl($table['qr_code'], true);
            } else {

                base64_image_content($img, $filename);

                $per = 0.5;
                list($width, $height) = getimagesize($filename);
                $n_w = $width * $per;
                $n_h = $height * $per;
                $new = imagecreatetruecolor($n_w, $n_h);
                $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
                imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
                imagedestroy($new);
                imagedestroy($img);

                $config = get_addon_config('alioss');
                $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
                $ret = $oss->uploadFile($config['bucket'], $name . ".jpg", $filename);
                $url = $ret['info']['url'];

                $tableModel->where('id', $table_id)->update(['qr_code' => "/" . $name . ".jpg"]);
                error_log("==oss=ret==" . json_encode($ret));

            }


            $this->success('', $url);
        }

    }


    public function orderDetail()
    {

        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $table = $tableOrderModel->with(['user'])->where('order_no', $order_no)->find();

        $shopModel = new Shop();
        $shopInfo = $shopModel->where('id', $table['shop_id'])->find();

        $table['profit'] = 0.00;
        if ($table['pay_amount'] > 0) {
            $profitModel = new Shoporderprofit();
            $where = array();
            $where['type'] = 'order';
            $where['from'] = 'tq';
            $orderProfit = $profitModel->where('order_id', $table['id'])->where($where)->find();
            if ($orderProfit) {
                $table['profit'] = $orderProfit['amount'];
            }
        }

        if($table['status'] == 'refund'){
            if($table['profit'] > 0){//用户主动退款后，扣留15%
                $newAmount = formatMoney($table['profit'] * 100 / (100 - $shopInfo['pay_rate'] - $shopInfo['ratio']));//反向计算新金额
                $table['pay_rate'] = formatMoney($newAmount * $shopInfo['pay_rate'] / 100);//店铺支付通道费
                $table['platform_profit'] = max(0.00, formatMoney($newAmount - $table['profit'] - $table['pay_rate']));//平台抽成
            }else{
                $table['pay_rate'] = 0.00;
                $table['platform_profit'] = 0.00;
            }
        }else{
            $table['pay_rate'] = formatMoney($table['pay_amount'] * $shopInfo['pay_rate'] / 100);//店铺支付通道费
            $table['platform_profit'] = max(0.00, formatMoney($table['pay_amount'] - $table['profit'] - $table['pay_rate']));//平台抽成
        }

        $table['take_out'] = 0;
        if ($table['status'] != 'refund') {
            if ($shopInfo['is_all'] == 1 || $shopInfo['profit_type'] == 2) {
                if ($table['mt_code'] != "" || $table['dou_code'] != "") {
                    //查询美团抖音的需扣除余额的值
                    $shopMtDyModel = new Shopmtdyprofit();
                    $mtDouProfit = $shopMtDyModel->where('order_id', $table['id'])->find();
                    if (!empty($mtDouProfit)) {
                        $table['take_out'] = $mtDouProfit['profit'];
                    }
                }
            }
        }
        if ($table['take_out'] > 0) {
            $table['mark'] = '全平台扣点订单，需扣除可提现余额 ' . $table['take_out'] . '元';
        }

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->where('order_id', $table['id'])->where('from', 'tq')->find();
        if ($table['status'] == 'doing') {
            $table['status_txt'] = "进行中";
        } else if ($table['status'] == 'done') {
            $table['status_txt'] = "已完成";
        } else if ($table['status'] == 'refund') {
            $table['status_txt'] = "已退款";
        }
        $table['create_time_text'] = date("Y-m-d H:i", $table['create_time']);
        $table['book_start'] = date("Y-m-d H:i", $table['book_start']);
        if ($table['book_end'] != -1) {
            $table['book_end'] = date("Y-m-d H:i", $table['book_end']);
        } else {
            $table['book_end'] = "";
        }
        $table['balance'] = 0;
        $table['dou_name'] = "";
        $table['mt_name'] = "";

        if ($balance) {
            $table['balance'] = $balance['amount'];
        }
        if ($table['dou_code'] != "") {

            $userDoucCodeModel = new Userdoucode();
            $dou = $userDoucCodeModel->where('dou_code', $table['dou_code'])->find();

            $shopDouModel = new Shopdou();
            $shopDou = $shopDouModel->where('sku_id', $dou['sku_id'])->where('shop_id', $dou['shop_id'])->find();
            if ($shopDou) {
                $table['dou_name'] = $shopDou['sku_name'];
            }
        }
        if ($table['mt_code'] != "") {

            $userMtCode = new Usermeituancode();
            $userMt = $userMtCode->where('mt_code', $table['mt_code'])->find();

            $shopMtModel = new Shopmeituan();
            $shopMt = $shopMtModel->where('id', $userMt['group_id'])->find();
            if ($shopMt) {
                $table['mt_name'] = $shopMt['title'];
            }
        }

        $this->success('', $table);
    }


    public function deleteTable()
    {

        $user = $this->auth->getUser();

        $table_id = $this->request->param('table_id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $table = $shopTableModel->where('id', $table_id)->find();
        if (!$table) {
            $this->error("台桌不存在");
        }
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $table['shop_id'])->find();
        if ($user['id'] != $shop['user_id']) $this->error("没有权限操作");
        $shopTableModel->where('id', $table['id'])->delete();
        $shopDeviceModel = new Shopdevice();
        $shopDeviceModel->where('room_id', $table['id'])->where('device_type', 'tq')->update(['room_id' => -1, 'bind_status' => -1]);

        $this->success('成功');
    }

    //管理端退款
    public function tableRefund()
    {

        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');
        $shopTableOrderModel = new \app\admin\model\Shoptableorder();
        $order = $shopTableOrderModel->where('order_no', $order_no)->find();

        if ($order['status'] == 'refund') $this->error('该订单已退款');
        if ($order['status'] == 'doing') $this->error('请先结束该订单，然后退款');

        $user = $this->auth->getUser();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();
        if ($shop['user_id'] != $user['id']) {
            $this->error("您没有权限操作退款");
        }

        //退实付
        $this->tableOrderPayRefund($order, $shop, $amount);

        //如果有余额支付回退余额
        if ($order['balance'] > 0) {
            //删除店铺支出余额
            $userBalanceModel = new Userbalance();
            $where['user_id'] = $order['user_id'];
            $where['order_id'] = $order['id'];
            $where['type'] = 'out';
            $where['from'] = 'tq';

            $userBalanceModel->where($where)->delete();
        }

        //如果是团购券 回滚
        if ($order['tuan_id'] != -1) {
            $userTuanModel = new Usertuan();
            $userTuanModel->where('id', $order['tuan_id'])->update(['status' => 'unuse']);
        }

        $this->success();
    }

    //订单实付退款
    protected function tableOrderPayRefund($order, $shop, $amount)
    {
        $shopOrderModel = new Shoptableorder();
        $refundAmount = 0.00;
        $new_pay_amount = 0.00;
        if ($amount > 0) {
            if ($amount > $order['pay_amount']) $this->error('退款金额不能大于支付金额');
            $new_pay_amount = formatMoney($order['pay_amount'] - $amount);
            $refundAmount = $amount;
        }

        if ($order['pay_amount'] > 0 && $refundAmount > 0) {

            $refundOrder_no = getOrderSn();

            $orgModel = new Org();
            $org = $orgModel->where('id', $order['org_id'])->find();

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
            $mno = $org['mno'];
            if ($shopMno && $shopMno['ratio'] == 100) {
                $mno = $shopMno['mno'];
            }
            $req = array();
            $req['mno'] = $mno;
            $req['ordNo'] = $refundOrder_no;
            $req['origOrderNo'] = $order['order_no'];
            $req['amt'] = $refundAmount;

            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);
            error_log("==admin=app=refund===" . $ret);
            $result = json_decode($ret, true);

            //判断原订单不一致的问题
            if ($result['code'] != '0000') {
                $this->error($result['msg']);
            }

            if ($result['respData']['bizCode'] != "0000") {
                $this->error($result['respData']['bizMsg']);
            }

            $shopOrderProfitModel = new Shoporderprofit();
            $userOrderProfitModel = new Userorderprofit();
            $platformModel = new Platform();
            if ($new_pay_amount > 0) {
                //部分退款，重新划分商家收益、通道支付费以及平台收益
                $new_pay_rate = formatMoney($new_pay_amount * $shop['pay_rate'] / 100);//支付通道费
                $new_profit = formatMoney($new_pay_amount * (100 - $shop['ratio'] - $shop['pay_rate']) / 100);//商家收益
                $new_rate = formatMoney($new_pay_amount - $new_profit - $new_pay_rate);//平台收益
                $new_amount = formatMoney($order['amount'] - $amount);//新的订单金额
                $shopOrderModel->where('id', $order['id'])->update(['amount' => $new_amount, 'pay_amount' => $new_pay_amount, 'update_time' => time()]);
                $shopOrderProfitModel->where('order_id', $order['id'])->where('shop_id', $order['shop_id'])->where('type', 'order')->where('from', 'tq')->update(['amount' => $new_profit]);

                $new_user_profit = formatMoney($new_pay_amount * $shop['agent_ratio'] / 100);
                $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->where('type', ' order')->update(['amount' => $new_user_profit]);
                $platformModel->where('order_id', $order['id'])->where('type', ' order')->where('from', 'qp')->update(['order_pay_amount' => $new_pay_amount, 'shop_amount' => $new_profit, 'rate' => $new_rate, 'agent_rate' => $new_user_profit]);

            } else {
                //全退，修改订单状态、删除收益记录
                $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);//修改订单状态
                $shopOrderProfitModel->where('order_id', $order['id'])->where('shop_id', $order['shop_id'])->where('type', 'order')->where('from', 'tq')->delete();
                $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->where('type', ' order')->delete();
                $platformModel->where('order_id', $order['id'])->where('type', ' order')->where('from', 'qp')->delete();
            }

        } else {
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);
        }
    }

}
